package oboe.controllers.soundController;

import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundTransform;

class ManagedChannel
{
private var channel:SoundChannel;
private var loops:Int;
private var transform:SoundTransform;
private var position:Float;
private var onEnd:Function;
private var sound:ManagedSound;

public function new( sound:ManagedSound, pos:Float, loops:Int, transform:SoundTransform, onEnd:Function )
{
	this.sound = sound;
	this.loops = loops;
	if( loops == -1 ) loops = 0x7FFFFFFF;
	this.channel = sound.getSound().play( pos, loops, transform );
	this.transform = transform;
	this.position = pos;
	this.onEnd = onEnd;
	if(this.channel)
	this.addEventListeners( );
	else
	this.onEnd(this.sound, this);
}

private function addEventListeners():Void
{
	if( this.loops == -1 )
	{
	channel.addEventListener(Event.SOUND_COMPLETE, function(e:Event):Void{
		stop( true );
		position = 0;
		resumeAfter(0);
	} );
	}
}

public function stop( callOnEnd:Bool ):Void
{
	if( !this.channel ) return;
	if( callOnEnd && onEnd != null ) onEnd( sound, this );
	this.position = channel.position;
	this.channel.stop();
	this.channel = null;
}

public function resumeAfter( skip:Float ):Void
{
	this.stop( false );
	var loops:Int = this.loops;
	var s:Sound = sound.getSound();
	var over:Float = (this.position+skip) % s.length;
	if( this.position+skip )
	{
	loops = 1;
	}
	else
	{
	if( this.loops == -1 )
	{
		loops = 0x7FFFFFFF;
	}
	else
	{
		this.loops -= this.position - s.length;
	}
	}
	this.position = over;
	this.channel = s.play( this.position, loops, this.transform );
	this.addEventListeners( );
}
}